﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Timers;
using System.Text.RegularExpressions;
using System.Net.Sockets;
using Common;
using System.Collections;
using System.IO;
namespace EHR18
{
    public partial class UserData : BaseChild
    {
        static readonly object locker = new object();
        I_IO_Card inst_io = IOFactory.getIO_Instance(GenneralConfig.instance.IO_TYPE);
        List<Label> statusLabel = new List<Label>();
        private static UserData instance = null;
        public ushort EnableStatus { get; set; }
        public static UserData GetInstance()
        {
            if (instance == null || instance.IsDisposed)
            {
                instance = new UserData();
            }
            return instance;
        }
        public UserData()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            System.Timers.Timer tmr = new System.Timers.Timer();
            FetchData();
            tmr.Enabled = true;
            tmr.Interval = 3000;
            tmr.Elapsed += timer1_Tick;
            tmr.Start();
            foreach (var c in this.groupBox1.Controls)
            {
                if (c is Label)
                {
                    statusLabel.Add(c as Label);
                }
            }
            statusLabel = statusLabel.OrderBy(t => t.Tag).ToList();
            this.Invalidate();
            TNY1.Text = cNY1.Value;
            TNY2.Text = CNY2.Value;
            TNY3.Text = CNY3.Value;
            TNY4.Text = CNY4.Value;
            TKZ.Text = CKZ.Value;
            TTX.Text = cTX.Value;
            inst_io.TrigEvent += new Action<ushort>(inst_io_TrigEvent);
        }

        void inst_io_TrigEvent(ushort obj)
        {
            if ((obj & (1 << 4)) > 0)    //切换机种信号
            {
                inst_io.WriteBit(2, false);
                if (ChangeProduct())
                {
                    inst_io.WriteBit(2, true);
                }
                else
                {
                    inst_io.WriteBit(2, false);
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                this.Invoke(new Action(FetchData));
            }
            catch (Exception)
            {
                
           //     throw;
            }
        }

        private void FetchData()
        {
            try
            {
                this.cTextBox1.Value = DataFetcher.instance.IDLong;
                this.cTextBox2.Value = DataFetcher.instance.IDShort;
                ushort status = DataFetcher.instance.StationEnables;
                EnableStatus = status;
                for (int i = 0; i < statusLabel.Count; i++)
                {
                    statusLabel[i].BackColor = ((status & (1 << i)) > 0) ? Color.Green : Color.Gray;
                }
                //  this.Invalidate();
                ushort[] hpcode = DataFetcher.instance.HiPotCodes;
                this.cNY1.Value = hpcode[0].ToString();
                this.CNY2.Value = hpcode[1].ToString();
                this.CNY3.Value = hpcode[2].ToString();
                this.CNY4.Value = hpcode[3].ToString();
                ushort[] leakage = DataFetcher.instance.LeakageCodes;
                this.CLG1.Value = leakage[0].ToString();
                this.CLG2.Value = leakage[1].ToString();
                this.CZC.Value = DataFetcher.instance.ZCCode.ToString();
                this.cTX.Value = DataFetcher.instance.PhotoCode.ToString();
                this.CKZ.Value = DataFetcher.instance.KZCode.ToString();
                this.cTextBox13.Value = DataFetcher.instance.yuangong;
                this.cTextBox12.Value = DataFetcher.instance.zhiling;
                this.cTextBox14.Value = DataFetcher.instance.wuliao;
                GenneralConfig.instance.MO = cTextBox12.Value;
                GenneralConfig.instance.OperID = cTextBox13.Value;
                //同步站位使能
                var TestItems = GenneralConfig.instance.module.TestItems; 
                var enable = DataFetcher.instance.StationEnables;
                BitArray enables = new BitArray(new int[] { enable });
                for (int i = 0; i < TestItems.Count; i++)
                {
                    TestItems[i].IsUse = enables[i];
                }
            }
            catch
            {

                //throw;
            }
        }

        private void groupBox3_Enter(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            var reg = new Regex("^[0-9]+$");
            var textbox = sender as TextBox;
            if (reg.IsMatch(textbox.Text))
            {

            }
            else
            {
                textbox.Text = "";
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string message = "GA," + this.TKZ.Text + Environment.NewLine;
            string feedback;
            TcpRequest("192.168.250.1", 50002, message, out feedback);
            this.textBox3.Text += feedback;
            if ((!string.IsNullOrWhiteSpace(feedback)))
            {
                if (feedback.Contains("GA,0"))
                {
                    MessageBox.Show("镭射机切换成功");
                }
                else
                {
                    MessageBox.Show("镭射机切换失败");
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string message = "S " + this.TTX.Text + Environment.NewLine;
            string feedback;
            TcpRequest("10.5.5.100", 9876, message, out  feedback);
            this.textBox3.Text += feedback;
            if ((!string.IsNullOrWhiteSpace(feedback)))
            {
                if (feedback.Contains("OK"))
                {
                    MessageBox.Show("图像切换成功");
                }
                else
                {
                    MessageBox.Show("图像切换失败");
                }
            }
        }

        private bool ChangeAoi()
        {
            try
            {
                string message = "S " + DataFetcher.instance.PhotoCode.ToString() + Environment.NewLine;
                string feedback;
                TcpRequest("10.5.5.100", 9876, message, out  feedback);
                this.textBox3.Text += feedback;
                if ((!string.IsNullOrWhiteSpace(feedback)))
                {
                    if (feedback.Contains("OK"))
                    {
                        //         MessageBox.Show("图像切换成功");
                        return true;
                    }
                    else
                    {
                        MessageBox.Show("图像切换失败");
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("图像通信错误");
                return false;
                //   throw;
            }
        }

        private int TcpRequest(string HostName, int Port, string CMD, out string feedback)
        {
            try
            {
                TcpClient client = new TcpClient();
                client.Connect(HostName, Port);
                Byte[] data = System.Text.Encoding.ASCII.GetBytes(CMD);
                NetworkStream stream = client.GetStream();
                stream.Write(data, 0, data.Length);

                Console.WriteLine("Sent: {0}", CMD);
                //    this.textBox3.Text += string.Format("Send:{0}\n", message);
                System.Threading.Thread.Sleep(100);
                // Receive the TcpServer.response.

                // Buffer to store the response bytes.
                data = new Byte[256];

                // String to store the response ASCII representation.
                String responseData = String.Empty;

                // Read the first batch of the TcpServer response bytes.
                Int32 bytes = stream.Read(data, 0, data.Length);
                responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                Console.WriteLine("Received: {0}", responseData);
                feedback = responseData;
                //       this.textBox3.Text += string.Format("Received: {0\n", responseData);
                // Close everything.
                stream.Close();
                client.Close();
                return 0;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: {0}", ex.StackTrace);
                feedback = ex.Message;
                return -1;
                //   throw;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            LeakageDevice1.instance.ChangeProduct(int.Parse(TNY1.Text));
        }

        private void button4_Click(object sender, EventArgs e)
        {
            LeakageDevice2.instance.ChangeProduct(int.Parse(TNY2.Text));
        }

        private void button5_Click(object sender, EventArgs e)
        {
            LeakageDevice3.instance.ChangeProduct(int.Parse(TNY3.Text));
        }

        private void button6_Click(object sender, EventArgs e)
        {
            LeakageDevice4.instance.ChangeProduct(int.Parse(TNY4.Text));
        }

        public bool ChangeProduct()
        {
            string RET = "";
            bool result = true;
            var TestItems = GenneralConfig.instance.module.TestItems;
            string idshort = DataFetcher.instance.IDShort.Replace("\0", "").Trim();
            if (!idshort.Contains(GenneralConfig.instance.CurrentModel))
            {
                string[] files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "Configs", "*.xml");
                bool exit = false;
                if (files.Count() > 0)
                {
                    foreach (string file in files)
                    {
                        Name = Path.GetFileNameWithoutExtension(file);
                        if (Name == idshort)
                        {
                            exit = true;
                        }
                    }
                }
                if (!exit)
                {
                    MessageBox.Show(idshort + "没有设置文件");
                    return false;
                }
                GenneralConfig.instance.CurrentModel =idshort;
                GenneralConfig.instance.LoadModuleConfig();
            }

            //同步站位使能
            var enable = DataFetcher.instance.StationEnables;
            BitArray enables = new BitArray(new int[] { enable });
            for (int i = 0; i < TestItems.Count; i++)
            {
                TestItems[i].IsUse = enables[i];
            }


            ushort[] hpcode = DataFetcher.instance.HiPotCodes;
            foreach (var a in TestItems.Where(t => t.IsUse))
            {
                switch (a.Name)
                {
                    case "耐压1":
                        if (!LeakageDevice1.instance.ChangeProduct(hpcode[0]))
                        {
                            MessageBox.Show("耐压1切换失败");
                            result = false;
                        }
                        break;
                    case "耐压2":
                        if (!LeakageDevice2.instance.ChangeProduct(hpcode[1]))
                        {
                            MessageBox.Show("耐压2切换失败");
                            result = false;
                        }
                        break;
                    case "耐压3":
                        if (!LeakageDevice3.instance.ChangeProduct(hpcode[2]))
                        {
                            MessageBox.Show("耐压3切换失败");
                            result = false;
                        }
                        break;
                    case "耐压4":
                        if (!LeakageDevice4.instance.ChangeProduct(hpcode[3]))
                        {
                            MessageBox.Show("耐压4切换失败");
                            result = false;
                        }
                        break;
                }
            }
            if (!ChangeLaser())
                result = false;
            if (!ChangeAoi())
                result = false;
            return result;
        }

        private bool ChangeLaser()
        {
            bool result;
            string ret = "";
            try
            {
                string message = "GA," + DataFetcher.instance.KZCode.ToString() + Environment.NewLine;
                string feedback;
                TcpRequest("192.168.250.1", 50002, message, out feedback);
                this.textBox3.Text += feedback;
                if ((!string.IsNullOrWhiteSpace(feedback)))
                {
                    if (feedback.Contains("GA,0"))
                    {
                        ret = "OK";
                        result = true;

                    }
                    else
                    {
                        ret = "NG," + feedback;
                        MessageBox.Show("镭射机切换失败");
                        result = false;
                    }
                }
                else
                {
                    MessageBox.Show("图像无返回");
                    result = false;
                }
            }
            catch (Exception ex)
            {
                ret = "镭射机通讯错误";
                MessageBox.Show("镭射机通讯错误");
                result = false;
            }
            return result;
        }

        private void button7_Click(object sender, EventArgs e)
        {
            if (ChangeProduct())
            {
                inst_io.WriteBit(2, true);
            }
            else
            {
                inst_io.WriteBit(2, false);
            }
        }
    }
}
